<template>
  <div >
    <input type="file" name="" style="opacity: 0;" id="file">
    <div class="avatar-uploader-icon">
      <img v-if="imageUrl" :src="imageUrl" class="avatar" id="avatar">
      <i v-else class="el-icon-plus" @click="submit"></i>
    </div>
    <p style="color: #606266;text-align: center;width: 400px;line-height: 40px;">点击上传头像 </p>
  </div>
</template>

<script>
import pubsub from 'pubsub-js'
export default {
name: 'Avatar',
    data() {
      return {
        imageUrl: ''
      };
    },
    methods: {
      submit(){
        document.querySelector('#file').click()
      }
    },
    mounted(){
      const file = document.getElementById('file')
      file.onchange = (event) => {
        let img = event.target.files[0]
        if (img.type === 'image/jpeg'){
          var reader = new FileReader()
          reader.readAsDataURL(img)
          reader.onload = (e) => {
            if (e.target.readyState == 2) {
              this.imageUrl = e.target.result
            }
          }
        }else {
          this.$message.error({message: '文件格式不正确!'})
        }
      }

      pubsub.subscribe('upload_img', (name, _data) => {
        if (_data){
          const options = {
            method: 'POST',
            headers: {
              "Content-Type": 'application/json'
            },
            body: JSON.stringify({
              url: this.imageUrl.replace('data:image/jpeg;base64,', '')
            })
          }
          fetch(`http://8.130.95.37:8085/Avatar`, options)/*.then(res => res.json())*/.then(res => {
            console.log(res)
          }).catch(err => console.log(err))
        }
      })

    }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    background-color: #ffffff;
    text-align: center;
    margin-left: 150px;
    
}
.avatar {
    /* width: 178px;
    height: 178px; */
    display: block;
}
img{
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    background-color: #ffffff;
    margin-top: -60%;
}



</style>
